package com.yycx.module.bus.provider.service.hy.impl;

import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.mybatis.query.CriteriaUpdate;
import com.yycx.common.security.OpenHelper;
import com.yycx.module.bus.client.entity.BusDept;
import com.yycx.module.bus.client.entity.hy.BusPolicyDept;
import com.yycx.module.bus.provider.mapper.hy.BusPolicyDeptMapper;
import com.yycx.module.bus.provider.service.hy.BusPolicyDeptService;
import com.yycx.common.mybatis.base.service.impl.BaseServiceImpl;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.module.system.provider.service.SysFormulaService;
import org.springframework.stereotype.Service;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.mybatis.query.CriteriaQuery;
import org.springframework.transaction.annotation.Propagation;
import com.yycx.common.mybatis.query.CriteriaSave;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 政策详情接口实现类
 *
 * @author flyme
 * @date 2023-07-18
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusPolicyDeptServiceImpl extends BaseServiceImpl<BusPolicyDeptMapper, BusPolicyDept> implements BusPolicyDeptService {

    @Resource
    private SysFormulaService sysFormulaService;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusPolicyDept bpd, EntityMap extra) {
        bpd.setCompanyId(OpenHelper.getCompanyId());
        return ResultBody.ok();
    }

    @Override
    public ResultBody beforeEdit(CriteriaUpdate<BusPolicyDept> cu, BusPolicyDept bpd, EntityMap extra) {
        return super.beforeEdit(cu, bpd, extra);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusPolicyDept> cq, BusPolicyDept bpd, EntityMap requestMap) {
        cq.select(BusPolicyDept.class, "*");
        cq.eq(BusPolicyDept.class, "policyDrugId");
        cq.addSelect(BusDept.class, "deptName");
        cq.orderByDesc("bpd.createTime");
        cq.createJoin(BusDept.class);
        return ResultBody.ok();
    }


    /**
     * 根据商品ID和部门ID查询
     *
     * @param policyDrugId
     * @param deptId
     * @param sendDate
     * @return
     */
    public BusPolicyDept findByPolicyDrugIdAndDeptId(Long policyDrugId, Long deptId, Date sendDate) {
        if (FlymeUtils.isNotEmpty(policyDrugId)) {
            CriteriaQuery<BusPolicyDept> cq = new CriteriaQuery(BusPolicyDept.class);
            cq.eq(true, "policyDrugId", policyDrugId);
            cq.eq(true, "deptId", deptId);
            cq.and(e -> e.isNull("endDate").or().ge(true, "endDate", sendDate));
            return getOne(cq,false);
        }
        return null;
    }
}
